import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import store from "../store";
import { deluser, inituserlist, adduser } from "../action/deluseraction";
import userModel from "../model/useraxios";

export class User extends Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      list: [],
      name: "",
      pwd: "",
    };
  }
  async componentDidMount() {
    let { data: list } = await userModel.query({});
    store.dispatch(inituserlist(list));
  }
  add = async () => {
    // console.log(this.state.name, this.state.pwd);
    if (this.state.name != "" && this.state.pwd != "") {
      await userModel.add({ name: this.state.name, pwd: this.state.pwd });
      let { data: list } = await userModel.query({});
        store.dispatch(inituserlist(list));
    }else{
        alert("用户名密码不能为空")
    }
  };
  render() {
    return (
      <div>
        <div>
          <div>
            用户名：
            <input
              type="text"
              value={this.state.name}
              onChange={(e) => {
                this.setState({
                  name: e.target.value,
                });
              }}
            ></input>
          </div>
          <div>
            密码：
            <input
              type="text"
              value={this.state.pwd}
              onChange={(e) => {
                this.setState({
                  pwd: e.target.value,
                });
              }}
            ></input>
          </div>
          <div>
            <button
              onClick={() => {
                this.add();
              }}
            >
              注册
            </button>
          </div>
        </div>
        <div className="table">
          <div className="tr">
            <div className="td">编号</div>
            <div className="td">姓名</div>
            <div className="td">密码</div>
            <div className="td">操作</div>
          </div>
          {this.props.user.map((item: any) => {
            return (
              <div className="tr" key={item.id}>
                <div className="td">{item.id}</div>
                <div className="td">{item.name}</div>
                <div className="td">{item.pwd}</div>
                <div
                  className="td"
                  onClick={async () => {
                    await userModel.del(item.id);
                    store.dispatch(deluser(item.id));
                  }}
                >
                  删除
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state: any) => ({
  user: state.user.list,
});

const mapDispatchToProps = {
  deluser,
  inituserlist,
  adduser,
};

export default connect(mapStateToProps, mapDispatchToProps)(User);
